package com.itheima.webaitliasserver.exception;

import com.itheima.webaitliasserver.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: xiaoZhang
 * @Description:
 * @Author: Zhang
 * @CreateDate: 2025-09-02 14:59
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handlerException(Exception e) {
        return Result.error(e.getMessage());
    }

    @ExceptionHandler
    public Result handlerDuplicateException(DuplicateKeyException e) {
        String message = e.getMessage();
        int index =  message.indexOf("Duplicate entry");
        String errorMsg = message.substring(index);
        String[] arr = errorMsg.split(" ");
        return Result.error(arr[2].replace("'" , "") + "已存在");
    }
}
